<template>
  <div class="project-interface-mnt layout flex-col">
    <div class="top">
      <div class="left">
        <a-button type="primary" @click="interfaceAddBtnClick()">
          <a-icon type="plus"/>
          添加
        </a-button>

        <a-button type="primary" @click="interfaceEditBtnClick()" :disabled="this.rowId == ''">
          <a-icon type="edit"/>
          编辑
        </a-button>
        <a-button type="primary" @click="interfaceRemoveBtnClick()" :disabled="this.selectedRowKeys.length < 1">
          <a-icon type="delete"/>
          删除
        </a-button>
        <a-button type="primary" @click="onSearch()">
          <a-icon type="redo"/>
          刷新
        </a-button>
        <a-button type="primary" icon="arrow-up" :disabled="rowId == ''" @click="moveUp()">上移</a-button>
        <a-button type="primary" icon="arrow-down" :disabled="rowId == ''" @click="moveDown()">下移</a-button>
      </div>
    </div>
    <a-table
      style="overflow-y: auto;height:84%"
      rowKey="id"
      bordered
      :columns="columns"
      :data-source="treeForm"
      :rowSelection="rowSelection"
      :pagination="true"
      :rowClassName="setRowClassName"
      :customRow="customRow"
    >
      <span slot-scope="text, row" slot="name">
        <a @click.stop.prevent="handlerGoToFormDetail(row)" class="a-edit">{{ text }}</a>
      </span>
      <!--接口请求方法-->
      <span slot="requestMethod" slot-scope="text">
        <span style="color: #6EB027;" v-if="text=='GET'">{{text}}</span>
        <span style="color: #E99F23;" v-if="text=='POST'">{{text}}</span>
        <span style="color: #498EE0;" v-if="text=='PUT'">{{text}}</span>
        <span style="color: #B6B6B6;" v-if="text=='PUT'">{{text}}</span>
        <span style="color: #C64947;" v-if="text=='DELETE'">{{text}}</span>
        <span style="color: #BBBBBB;" v-if="text=='COPY'">{{text}}</span>
        <span style="color: #CCCCCC;" v-if="text=='HEAD'">{{text}}</span>
        <span style="color: #CACACA;" v-if="text=='OPTIONS'">{{text}}</span>
        <span style="color: #B1B1B1;" v-if="text=='LINK'">{{text}}</span>
        <span style="color: #CCCCCC;" v-if="text=='UNLINK'">{{text}}</span>
        <span style="color: #A2A2A2;" v-if="text=='PURGE'">{{text}}</span>
        <span style="color: #BBBBBB;" v-if="text=='LOCK'">{{text}}</span>
        <span style="color: #CCCCCC;" v-if="text=='UNLOCK'">{{text}}</span>
        <span style="color: #CACACA;" v-if="text=='PROPFIND'">{{text}}</span>
        <span style="color: #B1B1B1;" v-if="text=='VIEW'">{{text}}</span>
      </span>
      <!--接口发布状态-->
      <span slot="interfaceStateId" slot-scope="text">{{ text }}</span>
      <!--是否启用-->
      <span slot="enable" slot-scope="text">
        <a-switch :default-checked="false" :checked="text"/>
      </span>
      <!--更新时间-->
      <span slot="modifyTime" slot-scope="text">{{ moment(text).format('YYYY/MM/DD HH:mm:ss') }}</span>
    </a-table>

  </div>
</template>

<script>
  import {getColumns} from '@/api/tableColumns'
  import projectManageService from '@/api/projectManageService'
  import moment from 'moment'

  const columns = [
    {
      title: '名称',
      dataIndex: 'interfaceName',
      scopedSlots: {
        customRender: 'name'
      }
    },
    {
      title: '分组',
      dataIndex: 'interfaceGroupName',
    },
    {
      title: '接口地址',
      dataIndex: 'requestUrl',
    },
    {
      title: '请求类型',
      dataIndex: 'requestMethod',
      scopedSlots: {
        customRender: 'requestMethod'
      }
    },
    {
      title: '发布状态',
      dataIndex: 'interfaceStateId',
      scopedSlots: {customRender: 'interfaceStateId'}
    },
    {
      title: '是否开启',
      dataIndex: 'enable',
      scopedSlots: {customRender: 'enable'}
    },
    {
      title: '修改时间',
      dataIndex: 'modifyTime',
      scopedSlots: {customRender: 'modifyTime'}
    }
  ]
  export default {
    name: 'ProjectInterface',
    data() {
      return {
        treeForm: [],
        activeKey: '',
        columns,
        formDialog: {open: false, title: ''},
        showId: false,
        selectedRowKeys: [],
        row: null,
        rowId: '',
        selectedRows: [],
        activeRevisionId: [],
        activeFormRevisionId: '',
        panes: []
      }
    },
    props: {
      project: {
        type: Object,
        default: () => ({})
      },
      type: {
        type: String,
        default: ''
      }
    },
    created() {
      this.projectInterfaceQuery();
    },
    methods: {
      moment,
      setRowClassName(record) {
        const isActiveRevisionId = this.activeRevisionId.some((item) => item === record.data.id)
        if (isActiveRevisionId) {
          return 'rowcolor'
        }
      },
      customRow(record, index) {
        return {
          // 行背景色
          style: {'background-color': record.id === this.rowId ? 'rgb(230, 247, 255)' : 'white'},
          on: {
            click: () => {
              this.row = record;
              this.rowId = record.id;
            },
            dblclick: () => {

            }
          }
        }
      },
      moveUpFun(list = [], id = '') {
        const index = list.findIndex((item) => item.id === id)
        const row = list[index]
        if (index === 0) {
          this.$message.error('已经是第一行，不能上移')
          return false
        } else {
          const lastId = list[index - 1].id
          list.splice(index - 1, 0, row)
          list.splice(index + 1, 1)
          return {lastId: lastId, list: list}
        }
      },
      moveDownFun(list = [], id = '') {
        const index = list.findIndex((item) => item.id === id)
        const row = list[index]
        if (index === list.length - 1) {
          this.$message.error('已经是最后一行，不能下移')
          return false
        } else {
          const nextId = list[index + 1].id
          list.splice(index + 2, 0, row)
          list.splice(index, 1)
          return {nextId: nextId, list: list}
        }
      },
      moveUp() {
        const businessFormId = this.rowId
        const obj = this.moveUpFun(this.treeForm, businessFormId)
        if (obj) {
          this.treeForm = obj.list
        }
      },
      moveDown() {
        const businessFormId = this.rowId
        const obj = this.moveDownFun(this.treeForm, businessFormId)
        if (obj) {
          this.treeForm = obj.list
        }
      },
      onSearch() {
        this.projectInterfaceQuery();
      },
      interfaceAddBtnClick() {
        this.showBusinessModelDialog({}, false);
      },
      interfaceEditBtnClick() {
        if (this.rowId === undefined || this.rowId === '' || this.rowId === null) {
          this.$message.error('请选择一行数据!')
        }
        projectManageService.projectInterfaceGet({interfaceId: this.rowId}).then((d) => {
          if (!d) {
            this.$message.error('项目接口：【' + this.row.interfaceName + '】已被删除！')
          } else {
            this.showBusinessModelDialog(d, true);
          }
        })
      },
      interfaceRemoveBtnClick() {
        this.$confirm({
          content: '确认删除项目接口？',
          okType: 'danger',
          onOk: () => {
            projectManageService.projectInterfaceDelete({interfaceIds: this.selectedRowKeys}).then((d) => {
              if (d) {
                this.projectInterfaceQuery();
                this.$message.success('删除成功!')
              } else {
                this.$message.error('删除失败!')
              }
            })
          }
        })
      },
      showBusinessModelDialog(projectInterface, update) {
        projectInterface = projectInterface || {};
        let title = (projectInterface.id ? '编辑' : '添加') + '项目接口';
        projectInterface = this.switchToBoolean(projectInterface);
        this.$dialog({
          title: title,
          content: () => import('@/views/investmentOnline/interfaceManage/dialog/ProjectInterfaceFormCtl'),
          width: 600,
          centered: true,
          maskClosable: false,
          validateContent: true,
          props: {
            project: this.project,
            data: projectInterface
          },
          on: {
            ok: (dialog) => {
              let data = dialog.getDialogCtl().getData();
              data.id = this.rowId;
              data.projectId = this.project.id;
              this.saveProjectInterface(data, update);
              dialog.closeDialog()
            },
            cancel() {
            }
          }
        })
      },
      saveProjectInterface(projectInterface, update) {
        if (update && projectInterface.id !== undefined && projectInterface.id !== null && projectInterface.id !== '') {
          projectManageService.projectInterfaceUpdate(projectInterface).then(
            (d) => {
              this.projectInterfaceQuery();
              this.$message.success('更新成功!')
            },
            (e) => {
              this.$message.error('更新失败!')
            }
          )
        } else {
          projectManageService.projectInterfaceSave(projectInterface).then(
            (d) => {
              this.projectInterfaceQuery();
              this.$message.success('保存成功!')
            },
            (e) => {
              this.$message.error('保存失败!')
            }
          )
        }
        this.rowId = '';
        this.row = null;
      },
      switchToBoolean(projectInterface) {
        const arr = Object.assign({}, projectInterface);
        arr.enable = !!projectInterface.enable;
        return arr;
      },
      handlerGoToFormDetail(record) {
        if (record === undefined || record.id === undefined || record.id === '' || record.id === null) {
          this.$message.error('请选择一行数据!')
        }
        this.rowId = record.id;
        this.row = record;
        projectManageService.projectInterfaceGet({interfaceId: record.id}).then((d) => {
          if (!d) {
            this.$message.error('项目接口：【' + this.row.interfaceName + '】已被删除！')
          } else {
            this.showBusinessModelDialog(d, true)
          }
        })
      },
      projectInterfaceQuery() {
        projectManageService.projectInterfaceQuery({projectId: this.project.id}).then(
          (d) => {
            this.treeForm = d;
          },
          (e) => {

          }
        )
      }
    },
    watch: {},
    computed: {
      rowSelection() {
        return {
          selectedRowKeys: this.selectedRowKeys,
          onChange: (selectedRowKeys, selectedRows) => {
            this.selectedRowKeys = selectedRowKeys
          }
        }
      }
    },
  }
</script>

<style lang="less" scoped>
  .project-interface-mnt {
    .left {
      .ant-btn {
        margin: 0px 10px 10px 0px
      }
    }
  }
</style>
